import { delProcess, getProcess } from "@/apis/process"
import {
  FolderAddOutlined,
  FileSearchOutlined,
  DeleteOutlined,
  CheckCircleOutlined,
  SyncOutlined,
  CloseCircleOutlined,
  ExportOutlined
} from '@ant-design/icons'
import { Breadcrumb, Button, Card, Table, Space, Popconfirm, Tag } from "antd"
import { useEffect, useState } from "react"
import { Link, Outlet, useNavigate } from "react-router-dom"
import './index.scss'

import CollectionCreateFormModal from "./components/CollectionCreateFormModal"
import { ExportExcel, paginationConfig } from "@/utils"

const Process = () => {
  const [data, setData] = useState([])

  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
      ellipsis: true,
      fixed: 'left',
      width: 100,
      defaultSortOrder: 'descend',  // 默认降序
      sorter: (a, b) => a.id - b.id,
      style: {
        maxWidth: 100
      }
    },
    {
      title: '运行算法名',
      dataIndex: 'algor_name',
      key: 'algor_name',
      align: 'center',
      ellipsis: true,
      filters: [
        {
          text: 'MOSL',
          value: 'MOSL',
        },
        {
          text: 'MOMA',
          value: 'MOMA',
        }
      ],
      onFilter: (value, record) => (
        // console.log(value, record)
        record.algor_name[0] === value
      ),
    },
    {
      title: '运行数据集名',
      dataIndex: 'file_name',
      key: 'file_name',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '当前状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      ellipsis: true,
      filters: [
        {
          text: '正在运行',
          value: 0,
        },
        {
          text: '运行成功',
          value: 1,
        },
        {
          text: '运行失败',
          value: 2,
        }
      ],
      onFilter: (value, record) => (
        // console.log(value, record)
        record.status === value
      ),
      render: (record) => (
        record === 0 ?
          <Tag className="status" color="processing" icon={<SyncOutlined spin />}>运行中</Tag> :
          record === 1 ?
            <Tag className="status" color="success" icon={<CheckCircleOutlined />}>运行成功</Tag> :
            <Tag className="status" icon={<CloseCircleOutlined />} color="error">运行失败</Tag>
      )
    },
    {
      title: '客户数量',
      dataIndex: 'c_num',
      key: 'c_num',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '容量类型',
      dataIndex: 'c_type',
      key: 'c_type',
      align: 'center',
      ellipsis: true,
      width: 100,
      style: {
        maxWidth: 100
      },
      render: (text) => (text)
    },
    {
      title: '时间窗类型',
      dataIndex: 'w_type',
      key: 'w_type',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '停止时间',
      dataIndex: 's_time',
      key: 's_time',
      align: 'center',
      ellipsis: true,
      render: (record) => record
    },
    {
      title: '迭代次数',
      dataIndex: 'i_time',
      key: 'i_time',
      align: 'center',
      ellipsis: true,
      render: (record) => record
    },
    {
      title: '运行时间',
      dataIndex: 'r_time',
      key: 'r_time',
      align: 'center',
      ellipsis: true,
      width: 200,
      render: (record) => record
    },
    {
      title: '操作',
      dataIndex: '',
      key: 'x',
      align: 'center',
      ellipsis: true,
      fixed: 'right',
      width: 250,
      render: (record) => {
        return (
          <Space>
            {
              record.status === 1 ? <Button
                icon={<FileSearchOutlined />}
                type="primary"
                style={{ background: "orange", }}
                onClick={() => clickShow(record)}
              >
                查看
              </Button> : null
            }

            <Popconfirm
              title="删除这条算法"
              description="你确定要删除这条算法吗?"
              onConfirm={() => confirm(record)}
              // onCancel={cancel}
              okText="是"
              cancelText="否"
            >
              <Button
                icon={<DeleteOutlined />}
                danger
                type="primary"
              >
                删除
              </Button>
            </Popconfirm>
          </Space>
        )
      }
    }
  ]


  // 删除算法气泡弹框确认删除记录
  const confirm = async (record) => {
    // console.log(record)
    await delProcess(record.process_id)
    getProcessList()
  }

  // 点击查看结果
  const navigate = useNavigate()
  const clickShow = (record) => {
    // console.log(record)
    const title = record.algor_name[0] + '_' + record.file_name
    navigate(`/process/result?id=${record.process_id}&&title=${title}&&i_time=${record.i_time}`)
  }

  const processedData = (data) => {
    if (data) {
      // console.log(data)
      return data.map((row, rowIndex) => {
        let rowData = {
          key: rowIndex + 1,
          id: rowIndex + 1,
          algor_name: row[11],
          file_name: row[2],
          c_num: row[3],
          c_type: row[4],
          w_type: row[5],
          s_time: row[6],
          i_time: row[7],
          r_time: row[8],
          algor_id: row[1],
          status: row[9],
          process_id: row[0]
        }
        return rowData
      })
    }
  }


  const getProcessList = async () => {
    const res = await getProcess()
    setData(processedData(res))
  }

  useEffect(() => {
    const getProcessList = async () => {
      const res = await getProcess()
      setData(processedData(res))
    }
    getProcessList()

    // 每秒轮询一次
    const intervalId = setInterval(getProcessList, 1000)

    // 清除定时器
    return () => clearInterval(intervalId)
  }, [])

  // 添加运行
  const [add, setAdd] = useState(false)
  // const onCreate = async (values) => {
  //   // console.log('Received values of form: ', values)
  //   // setOpen(false)
  //   const res = await getProcess()
  //   setData(processedData(res))
  // }


  return (
    <div>
      <Card
        title={
          <Breadcrumb items={[
            { title: <Link to={'/'}>首页</Link> },
            { title: '运行列表' },
          ]}
            className='breadcrumb'
          />
        }
      >
        <Space style={{
          marginTop: 10,
          marginBottom: 20
        }}>
          <Button
            type="primary"
            style={{
              backgroundColor: '#eb2f96'
            }}
            icon={<FolderAddOutlined />}
            onClick={() => setAdd(true)}
          >
            新增运行
          </Button>
          <Button type='primary' onClick={() => ExportExcel(columns, data, 'ProcessList')} icon={<ExportOutlined />}>导出表格</Button>
        </Space>

        <Table
          columns={columns}
          dataSource={data}
          bordered
          pagination={paginationConfig}
          scroll={{
            y: 'calc(100vh - 400px)',
            x: '110vw',
          }}
        />

        <Outlet />

      </Card>

      <CollectionCreateFormModal
        open={add}
        data={data}
        // onCreate={onCreate}
        onCancel={() => setAdd(false)}
      // getAlgorList={getAlgorList}
      />
    </div>
  )
}

export default Process